import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import * as Utils from '@/utils/utils';
import AccountJS from '@/utils/account';
import Enumerable from 'linq';
import moment from 'moment';

import {
  Row,
  Col,
  Card,
  Table,
  Form,
  Button,
  Input,
  Icon,
  Select,
  DatePicker,
  Dropdown,
  Menu,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './styles.less';
import RadioGroup from 'antd/lib/radio/group';

const { Item: FormItem } = Form;
const { Option } = Select;
const { RangePicker, MonthPicker } = DatePicker;

const ModelName = 'profit';

@connect(({ profit, loading }) => ({
  loading: loading.models[ModelName],
  model: profit,
}))
@Form.create()
class Comp extends PureComponent {
  state = {};

  componentDidMount() {
    this.doQuery();
  }

  doQuery(cond) {
    const { dispatch, model } = this.props;
    let payload = {
      ...model.qc,
      ...cond,
    };
    dispatch({
      type: `${ModelName}/get`,
      payload: payload,
    });
  }

  handlePageChange = (number, size) => {
    const cond = {
      pageSize: size,
      pageNumber: number,
    };
    this.doQuery(cond);
  };

  handleSearch = e => {
    e.preventDefault();

    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log('FV', fieldsValue);

      let payload = {
        ...fieldsValue,
        year: fieldsValue.yearMonth ? fieldsValue.yearMonth.year() : 0,
        month: fieldsValue.yearMonth ? fieldsValue.yearMonth.month() + 1 : 0,
        lockDateStart:
          fieldsValue.lockDate &&
            Array.isArray(fieldsValue.lockDate) &&
            fieldsValue.lockDate.length === 2
            ? Utils.getChineseDate(fieldsValue.lockDate[0])
            : null,
        lockDateEnd:
          fieldsValue.lockDate &&
            Array.isArray(fieldsValue.lockDate) &&
            fieldsValue.lockDate.length === 2
            ? Utils.getChineseDate(fieldsValue.lockDate[1])
            : null,
      };
      delete payload.yearMonth;
      delete payload.lockDate;
      this.doQuery(payload);
    });
  };

  handleFormReset = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.resetFields();

    dispatch({
      type: `${ModelName}/reSetQC`,
    });
  };

  queryForm = () => {
    const {
      form: { getFieldDecorator },
      model,
    } = this.props;

    const { qc } = model;

    const colSpanLayout = {
      xs: 24,
      md: 12,
      lg: 5,
    };

    const formLayout = {
      labelCol: {
        xs: { span: 7 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 17 },
        sm: { span: 17 },
      },
    };

    return (
      <Form onSubmit={this.handleSearch}>
        <Row gutter={1} className={styles.dataRow}>
          <Col {...colSpanLayout}>
            <FormItem label="关键字" {...formLayout}>
              {getFieldDecorator('keyword', {
                initialValue: qc.keyword,
              })(<Input placeholder="姓名、单号、SO号、金额" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="年月" {...formLayout}>
              {getFieldDecorator('yearMonth', {
                initialValue:
                  qc.year && qc.year > 0 && qc.month && qc.month > 0
                    ? moment(`${qc.year}-${qc.month}`)
                    : null,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="核销日期" {...formLayout}>
              {getFieldDecorator('lockDate', {
                initialValue:
                  qc.lockDateStart && qc.lockDateEnd
                    ? [moment(qc.lockDateStart), moment(qc.lockDateEnd)]
                    : null,
              })(<RangePicker />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="主单核销" {...formLayout}>
              {getFieldDecorator('isBillLock', {
                initialValue: qc.isBillLock
              })(
                <Select placeholder="请选择">
                  <Option value={-1}>全部</Option>
                  <Option value={0}>未核销</Option>
                  <Option value={1}>已核销</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={3} style={{ float: 'right' }} >
            <div>
              <Button type="primary" htmlType="submit">
                查询
            </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
            </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const { model, loading } = this.props;
    const { data } = model;

    const columns = [
      {
        title: '#',
        dataIndex: 'ReNo',
        render: (text, record, index) => (
          <span> {index + 1 + (data.currentPage - 1) * data.pageSize} </span>
        ),
      },
      {
        title: '业务员',
        dataIndex: 'salerName',
      },
      {
        title: '年月',
        dataIndex: 'yearMonth',
        render: (text, record) => (
          <span>
            {record.year}-{record.month}
          </span>
        ),
      },
      {
        title: '单号',
        dataIndex: 'billNumber',
        render: text => <Link to={`/Bill/${text}/inv`}>{text}</Link>,
      },
      {
        title: 'SO号',
        dataIndex: 'so',
      },
      {
        title: '主单核销',
        dataIndex: 'lockDate',
        render: (text, record) => Utils.getChineseDate(record.lockDate, '未核销'),
      },
      {
        title: '金额',
        dataIndex: 'profit',
        align: 'right',
        render: (text, record) => <span>{AccountJS.format(record.profit, 2)}</span>,
      },
      {
        title: '币种',
        dataIndex: 'currencyId',
        align: 'left',
        render: (text, record) => <span>{record.currencyName}</span>,
      },
    ];

    const footerContent = () => {
      const groupSum = Enumerable.from(data.tag)
        .groupBy('$.currencyName', null, (key, g) => {
          const result = {
            currency: key,
            total: g.sum('$.profit'),
          };
          return result;
        })
        .toArray();

      return (
        <div className={styles.relFooter}>
          {groupSum.map(item => (
            <p key={item.currency}>
              <span className={styles.total}>{AccountJS.format(item.total, 2)}</span>
              <span className={styles.currencyName}>{item.currency}</span>
            </p>
          ))}
        </div>
      );
    };

    const groupContent = () => {
      const groupSaler = Enumerable.from(data.tag)
        .groupBy('$.salerName', null, (key, g) => {
          const result = {
            salerName: key,
            curs: g.select('$.currencyName').toArray(),
            profits: g.select('$.profit').toArray(),
          };
          return result;
        }).toArray();

      return (
        <div gutter={24} className={styles.groupRow} style={{ height: '6em', display: 'flex', float: 'left', marginBottom: '6px' }} >
          {groupSaler.map(item => {
            var key = item.salerName;
            return (<Card style={{ height: '6em', width: '200px', marginRight: '8px' }} key={key} gutter={24} key={item.salerName}>
              <span>{key}</span>
              {item.profits.map((p, index) => {
                var pf = item.profits[index];
                var cur = item.curs[index];
                return (
                  <div key={pf + cur + ''}>
                    <span>{AccountJS.format(pf, 2)}</span>
                    <span>{' ' + cur}</span>
                  </div>
                );
              })
              }
            </Card>)
          }
          )}
        </div>
      )
    }

    return (
      <PageHeaderWrapper>
        <div className={styles.tableListForm}>{this.queryForm()}</div>
        <Card bordered={false}>
          {data.dataList && data.dataList.length > 0 && groupContent()}
          <Table
            style={{ marginTop: '12px' }}
            rowKey={record => String(record.billId).concat(String(record.currencyId))}
            size="small"
            loading={loading}
            dataSource={data.dataList}
            columns={columns}
            pagination={{
              showSizeChanger: true,
              total: data.totalCount,
              pageSize: data.pageSize,
              current: data.currentPage,
              onChange: this.handlePageChange,
              onShowSizeChange: this.handlePageChange,
              showTotal: (total, range) => `共${total}项，当前显示 ${range[0]}-${range[1]}`,
            }}
            footer={() => footerContent()}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Comp;
